<template>
  <div>
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="120px"
      v-loading="loading"
    >
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="收款名称" prop="invoiceName">
            <el-input
              v-model="formData.invoiceName"
              placeholder="请输入收款名称"
              :disabled="!isEditing"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="纳税识别号" prop="taxNumber">
            <el-input
              v-model="formData.taxNumber"
              placeholder="请输入纳税识别号"
              :disabled="!isEditing"
            />
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="地址" prop="address">
            <el-input
              v-model="formData.address"
              placeholder="请输入地址"
              :disabled="!isEditing"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="电话" prop="phone">
            <el-input
              v-model="formData.phone"
              placeholder="请输入电话"
              :disabled="!isEditing"
            />
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="开户银行名称" prop="bankName">
            <el-input
              v-model="formData.bankName"
              placeholder="请输入开户银行名称"
              :disabled="!isEditing"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="开户银行账号" prop="bankAccount">
            <el-input
              v-model="formData.bankAccount"
              placeholder="请输入开户银行账号"
              :disabled="!isEditing"
            />
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-form-item>
        <el-button
          v-if="!isEditing && !hasData"
          type="primary"
          @click="handleAdd"
        >
          <Icon icon="ep:plus" /> 新增收款信息
        </el-button>
        <el-button
          v-if="!isEditing && hasData"
          type="primary"
          @click="handleEdit"
        >
          <Icon icon="ep:edit" /> 编辑收款信息
        </el-button>
        <el-button
          v-if="isEditing"
          type="primary"
          @click="handleSave"
          :loading="saving"
        >
          保存
        </el-button>
        <el-button
          v-if="isEditing"
          @click="handleCancel"
        >
          取消
        </el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { AccountingCompaniesInvoiceApi, AccountingCompaniesInvoiceVO } from '@/api/oa/accountingcompanies/invoice'

/** 收款信息表单 */
defineOptions({ name: 'PaymentForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const props = defineProps<{
  companyId: number
}>()

const loading = ref(false) // 加载中
const saving = ref(false) // 保存中
const isEditing = ref(false) // 是否处于编辑状态
const hasData = ref(false) // 是否有数据

const formRef = ref() // 表单引用
const formData = ref<Partial<AccountingCompaniesInvoiceVO>>({
  id: undefined,
  companyId: undefined,
  invoiceName: '',
  address: '',
  bankName: '',
  taxNumber: '',
  phone: '',
  bankAccount: '',
  infoType: 2 // 收款信息类型
})

const formRules = reactive({
  invoiceName: [{ required: true, message: '收款名称不能为空', trigger: 'blur' }],
  taxNumber: [{ required: true, message: '纳税识别号不能为空', trigger: 'blur' }]
})

/** 获取收款信息 */
const getPaymentData = async () => {
  loading.value = true
  try {
    const data = await AccountingCompaniesInvoiceApi.getAccountingCompaniesInvoiceListByCompanyIdAndType(props.companyId, 2)
    if (data && data.length > 0) {
      // 有数据，填充表单
      const paymentData = data[0]
      formData.value = {
        id: paymentData.id,
        companyId: paymentData.companyId,
        invoiceName: paymentData.invoiceName,
        address: paymentData.address,
        bankName: paymentData.bankName,
        taxNumber: paymentData.taxNumber,
        phone: paymentData.phone,
        bankAccount: paymentData.bankAccount,
        infoType: 2
      }
      hasData.value = true
    } else {
      // 没有数据，清空表单
      resetForm()
      hasData.value = false
    }
  } finally {
    loading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    companyId: props.companyId,
    invoiceName: '',
    address: '',
    bankName: '',
    taxNumber: '',
    phone: '',
    bankAccount: '',
    infoType: 2
  }
  formRef.value?.resetFields()
}

/** 新增收款信息 */
const handleAdd = () => {
  isEditing.value = true
  resetForm()
}

/** 编辑收款信息 */
const handleEdit = () => {
  isEditing.value = true
}

/** 保存收款信息 */
const handleSave = async () => {
  // 校验表单
  if (!formRef.value) return
  const valid = await formRef.value.validate()
  if (!valid) return
  
  saving.value = true
  try {
    const data = formData.value as AccountingCompaniesInvoiceVO
    // 统一使用创建或更新方法
    await AccountingCompaniesInvoiceApi.createOrUpdateAccountingCompaniesInvoice(data)
    message.success(data.id ? t('common.updateSuccess') : t('common.createSuccess'))
    isEditing.value = false
    // 重新获取数据
    await getPaymentData()
  } finally {
    saving.value = false
  }
}

/** 取消编辑 */
const handleCancel = () => {
  isEditing.value = false
  // 重新获取数据，恢复原始状态
  getPaymentData()
}

// 监听公司ID变化，重新获取数据
watch(() => props.companyId, (newVal, oldVal) => {
  console.log('PaymentForm - companyId changed:', { oldVal, newVal })
  if (newVal) {
    getPaymentData()
  }
}, { immediate: true })

defineExpose({ getPaymentData }) // 提供 getPaymentData 方法，用于外部调用
</script> 